package com.kaiwukj.android.ufamily.utils;

import android.content.Context;
import android.media.MediaMetadataRetriever;

import com.blankj.utilcode.util.LogUtils;
import com.qiniu.pili.droid.shortvideo.PLErrorCode;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;

import java.io.File;

/**
 * 视频处理工具类
 */
public class VideoUtils {

    private static VideoUtils instance;
    private static final int COMPRESS_LEVEL = 2;

    private VideoUtils() {
    }


    public static VideoUtils getInstance() {
        if (instance == null) {
            instance = new VideoUtils();
        }
        return instance;
    }

    /**
     * 压缩
     *
     * @param context       Context
     * @param videoPath     local file path
     * @param compressLevel 压缩等级 0-8(建议6)
     */
    public synchronized void startCompressed(Context context, String videoPath, int compressLevel, OnVideoDealListener listener) {
        if (compressLevel < 0 || compressLevel > 8) {
            compressLevel = COMPRESS_LEVEL;
        }
        String tempPath = context.getCacheDir().getPath();
        //PLShortVideoTranscoder初始化，三个参数，第一个context，第二个要压缩文件的路径，第三个视频压缩后输出的路径

        PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(context, videoPath, tempPath + File.separator + System.currentTimeMillis() + ".mp4");
        MediaMetadataRetriever retr = new MediaMetadataRetriever();
        retr.setDataSource(videoPath);
        String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
        String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 视频宽度
        String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); // 视频旋转方向
        //startTime = System.currentTimeMillis();
        mShortVideoTranscoder.transcode(Integer.parseInt(width), Integer.parseInt(height), getEncodingBitrateLevel(compressLevel), new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String s) {
                if (listener != null) listener.onSuccess(s);
            }

            @Override
            public void onSaveVideoFailed(final int errorCode) {
                LogUtils.e("errorCode:" + errorCode);
                String errorMsg = "压缩失败";
                switch (errorCode) {
                    case PLErrorCode.ERROR_NO_VIDEO_TRACK:
                        errorMsg = "该文件没有视频信息！";
//                                ToastUtils.getInstance().showToast("该文件没有视频信息！");
                        break;
                    case PLErrorCode.ERROR_SRC_DST_SAME_FILE_PATH:
                        errorMsg = "源文件路径和目标路径不能相同！";
//                                ToastUtils.getInstance().showToast("源文件路径和目标路径不能相同！");
                        break;
                    case PLErrorCode.ERROR_LOW_MEMORY:
                        errorMsg = "手机内存不足，无法对该视频进行时光倒流！";
//                                ToastUtils.getInstance().showToast("手机内存不足，无法对该视频进行时光倒流！");
                        break;
                    default:
//                                ToastUtils.getInstance().showToast("transcode failed: " + errorCode);
                        errorMsg = errorCode + ":文件处理失败";
                        break;
                }
                if (listener != null) listener.onFailed(errorCode, errorMsg);
            }

            @Override
            public void onSaveVideoCanceled() {
                // handler.sendEmptyMessage(101);
//                LogUtil.e("onSaveVideoCanceled");
                listener.onFailed(100, "操作已取消");
            }

            @Override
            public void onProgressUpdate(float percentag) {
                //  percentage = percentag;
                // handler.sendEmptyMessage(100);
//                LogUtil.e("onProgressUpdate==========" + percentage);
                listener.onProgressUpdate(percentag);
            }
        });
    }

    /**
     * 设置压缩质量
     *
     * @param position
     * @return
     */
    private int getEncodingBitrateLevel(int position) {
        return ENCODING_BITRATE_LEVEL_ARRAY[position];
    }

    /**
     * 选的越高文件质量越大，质量越好,对应压缩后尺寸更大
     */
    public static final int[] ENCODING_BITRATE_LEVEL_ARRAY = {
            500 * 1000,
            800 * 1000,
            1000 * 1000,
            1200 * 1000,
            1600 * 1000,
            2000 * 1000,
            2500 * 1000,
            4000 * 1000,
            8000 * 1000,
    };

    public OnVideoDealListener mListener;

    public interface OnVideoDealListener {
        void onSuccess(String filePath);

        void onFailed(int errorCode, String errorMsg);

        void onProgressUpdate(float progress);

    }

}
